﻿using System;
using System.Web.UI;

namespace JQueryControlToolkit 
{
	public static class ControlExtensions
	{
		/// <summary>
		/// Finds a Control recursively by its ID. Note: finds the first match and exits.
		/// From: http://www.west-wind.com/Weblog/posts/5127.aspx
		/// </summary>
		/// <param name="rootControl">Control under which to search</param>
		/// <param name="controlId">ID of the control you are searching for</param>
		/// <returns>First control matching Id. Returns null if not found.</returns>
		public static Control FindControlRecursive(Control rootControl, string controlId)
		{
			if (rootControl.ID == controlId)
				return rootControl;

			foreach (Control control in rootControl.Controls)
			{
				Control foundControl = FindControlRecursive(control, controlId);
				if (foundControl != null)
				{
					return foundControl;
				}
			}

			return null;
		}

		/// <summary>
		/// Finds a Control recursively by its Type. Note: finds the first match and exits.
		/// From: http://www.west-wind.com/Weblog/posts/5127.aspx
		/// </summary>
		/// <param name="rootControl">Control under which to search</param>
		/// <param name="type">Type of the control to find.</param>
		/// <returns>First control of the Type. Returns null if none found.</returns>
		public static Control FindControlRecursive(Control rootControl, Type type)
		{
			if (rootControl.GetType().Equals(type))
				return rootControl;

			foreach (Control control in rootControl.Controls)
			{
				Control foundControl = FindControlRecursive(control, type);
				if (foundControl != null)
				{
					return foundControl;
				}
			}

			return null;
		}

	}

}